package com.camtc.camcenter.base.service.impl;

import com.camtc.camcenter.dao.entity.BaseEntity;
import com.camtc.camcenter.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 基础服务实现
 *
 * @author
 * @date
 */

public abstract class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> {

    /**
     * 操作对象
     */
    protected JpaRepository jpaRepository;

    /**
     * 初始化查询对象【抽象】
     */
    public abstract void initJpaRepository();

    /**
     * 父类无参构造，将jpaRepository引用指向子类对象
     */
    protected BaseServiceImpl() {
        initJpaRepository();
    }

    @Override
    public List<T> findAll(T t) {
        return jpaRepository.findAll(Example.of(t));
    }

    @Override
    public List<T> findAll(T t, Sort sort) {
        return jpaRepository.findAll(Example.of(t), sort);
    }

    @Override
    public Page<T> findByPage(T t, int page, int rows) {
        return jpaRepository.findAll(Example.of(t), PageRequest.of(page, rows));
    }

    @Override
    public Page<T> findByPageAndSort(T t, int page, int rows, Sort sort) {
        return jpaRepository.findAll(Example.of(t), PageRequest.of(page, rows, sort));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public T insert(T t) {
        return (T) jpaRepository.save(t);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public T update(T t) {
        return (T) jpaRepository.saveAndFlush(t);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String id) {
        jpaRepository.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatch(List<String> ids) {
        jpaRepository.deleteAll(ids);
    }
}
